<?php
//
// +------------------------------------------------------------------------+
// | PHP Version 5.4                                                        |
// +------------------------------------------------------------------------+
// | Copyright (c) All rights reserved.                                     |
// +------------------------------------------------------------------------+
// | 世纪车来车往(北京）网络科技有限公司 版权所有！                         |
// | TEL:010-63732365  HOTLINE:400-6688-365  EMAIL:clcw@clcw.com.cn         |
// | $Revision: 1.0 $                                                       |
// +------------------------------------------------------------------------+
// | Author: songaimin@clcw.com.cn  Blog:http://blog.csdn.net/samxx8        |
// +------------------------------------------------------------------------+
//
namespace AuctionCore\Issue;

use AuctionCore\Finance\Loan;
use AuctionCore\Other\Inbox;
use AuctionCore\System\AuctionException;
use AuctionCore\CarResource\Car;
use AuctionCore\CarResource\CarModel;
use AuctionCore\CarDealer\Dealer;
use AuctionCore\AuctionOrder\AuOrder;
use AuctionCore\Account\Back\Employee;
use AuctionCore\Other\Address;
use AuctionCore\CarResource\BreachCar;
use AuctionCore\CarDealer\MyAuctioned;
use AuctionCore\CarDealer\AssetCenter;
use AuctionCore\Finance\DealerRefund;
use AuctionCore\Finance\DealerCompensate;
use AuctionCore\Other\XimuApi;
use AuctionCore\AntNest\UserCenter;
use Think\Log;

/**
 * 车商争议模型
 *
 * @author   Administrator
 */
class DealerIssue
{
    const STATUS_PENDING = 0; // 待处理
    const STATUS_SUCCESS = 1; // 协商成功
    const STATUS_FAILD = 2; // 车商违约
    const STATUS_OUR_FAILD = 3; // 我方违约

    const TRANSFER_BY_COMPANY = 0; // 公司过户
    const TRANSFER_BY_PERSON = 1; // 车商自己过户

    const ISSUE_TYPE_DISAGREE = 1; // 车况不符
    const ISSUE_TYPE_VIOLATE = 2; // 违约(超时验车)
    const ISSUE_TYPE_TRANSFER = 3; // 过户争议
    const ISSUE_TYPE_PAY = 4; // 结算争议
    const ISSUE_TYPE_TRANSFERING = 5; // 过户中争议
    const ISSUE_TYPE_PAY_PENDING = 6; // 待收款争议
    const ISSUE_TYPE_PAY_AUDIT = 7; // 核实收款


    /*争议数据状态集合*/
    public static $dataStatus = array(
        'pending' => self::STATUS_PENDING,
        'success' => self::STATUS_SUCCESS,
        'faild' => self::STATUS_FAILD,
        'ourfaild' => self::STATUS_OUR_FAILD
    );

    /*过户类型*/
    public static $transferType = array(
        'company' => self::TRANSFER_BY_COMPANY,
        'person' => self::TRANSFER_BY_PERSON,
    );

    /*争议类型*/
    public static $issueTypes = array(
        'disagree' => array('code' => self::ISSUE_TYPE_DISAGREE, 'title' => '车况不符'),
        'violate' => array('code' => self::ISSUE_TYPE_VIOLATE, 'title' => '验车超时'),
        'transfer' => array('code' => self::ISSUE_TYPE_TRANSFER, 'title' => '待过户争议'),
        'transfering' => array('code' => self::ISSUE_TYPE_TRANSFERING, 'title' => '过户中争议'),
        'pay' => array('code' => self::ISSUE_TYPE_PAY, 'title' => '结算争议'),
        'pay_pending' => array('code' => self::ISSUE_TYPE_PAY_PENDING, 'title' => '待收款争议'),
        'pay_audit' => array('code' => self::ISSUE_TYPE_PAY_AUDIT, 'title' => '核实收款争议')
    );

    protected $order_id = null;

    /**
     * 构造
     *
     * @param    int $order_id 拍单编号 或 拍单id
     *
     * @return   void
     */
    public function __construct($order_no_or_id = '')
    {
        $this->order_id = $order_no_or_id;
    }

    private function checkOrderID()
    {
        if (!is_numeric($this->order_id)) {
            $r = M('order')->field('order_id')->where("order_no='{$this->order_id}'")->find();
            if ($r && count($r) > 0) {
                $this->order_id = $r['order_id'];
            } else {
                AuctionException::make_throw('700002');
            }
        }
    }

    /**
     * 车商争议详情。
     *
     * @return   Array
     */
    public static function detail_by_issue_id($issue_id)
    {
        $cond = array(
            'issue_id' => $issue_id
        );
        $res = M('dealer_issue')->where($cond)->find();
        return $res;
    }

    /**
     * 按照order_id获取车商争议记录
     *
     * @param integer $page
     *
     * @return mix
     */
    public static function getIssueInfoByOrderID($orderID)
    {
        if (!isset($orderID) || !is_numeric($orderID)) {
            AuctionException::make_throw('1700001');
        }
        $cols = 'di.issue_id,di.order_id,di.issue_type,di.man_id,di.status as issue_status,di.updatetime as issue_done_time,di.emp_id as issue_done_empid,di.transfer_type,di.cut_down_price,di.remark,di.updatetime';
        $map = array(
            'order_id' => $orderID
        );
        $res = M('dealer_issue')->alias('di')->field($cols)->where($map)->find();
        return $res;
    }

    /**
     * 获取车商争议列表
     *
     * @param integer $page
     * @param int     $size
     * @param unknown $paramer
     *
     * @return multitype:unknown string
     */
    public function issue_dealer_list($page = 1, $size = 10, $params)
    {
        $page = (int)$page < 1 ? 1 : (int)$page;
        $size = (int)$size < 1 ? 10 : (int)$size;
        $order = "o.last_time desc";
        $map = array();
        // if (isset($params['status']) && is_numeric($params['status'])) {
        //     // $map .= "di.status=" . $params['status'];
        //     $map[] = array('di.status' => $params['status']);
        // }
        if ($params['status'] == 0) {
            $map[] = array('di.status' => 0);
        } elseif ($params['status'] == 1) {
            $map[] = array('di.status' => 1);
        } elseif ($params['status'] == 2) {
            // $map[] = array('di.status' => 2),array('di.status' => 3);
            $map['di.status'] = array(array('eq', 2), array('eq', 3), 'or');
        }
        if (isset($params['issue_type']) && is_numeric($params['issue_type'])) {
            // $map .= "di.status=" . $params['status'];
            $map[] = array('di.issue_type' => $params['issue_type']);
        }
        if (!empty($params['location_area'])) {
            $map[] = array('c.location_area' => $params['location_area']);
        }
        if (isset($params['comeFrom']) && $params['comeFrom'] !== '' && $params['comeFrom'] != '-2') {
            $map[] = array('co.comefrom' => $params['comeFrom']);
        }
       /* if (!empty($params['order_no'])) {
            $where['o.order_no'] = array('eq', $params['order_no']);
            $where['cd.contact_person'] = array('eq', $params['order_no']);
            $where['cd.contact_mobile'] = array('eq', $params['order_no']);
            $where['_logic'] = 'or';
            $map['_complex'] = $where;
        }*/
        if (!empty($params['order_no'])) {
            if(is_numeric($params['order_no'])){
                $uc = new UserCenter();
                $info1 = $uc->info_bymobile($params['order_no'],2,1);
                $where['du.uid'] = array('eq',$info1['account_id']);
            }else{
                $where['o.order_no'] = array('eq', $params['order_no']);
                $where['cd.contact_person'] = array('eq', $params['order_no']);
                $where['_logic'] = 'or';
            }
            $map['_complex'] = $where;
        }
        //付款状态
        $pay_status = $params['pay_status'];
        if ($pay_status == 1) {                           //待付首款
            $map['c.pay_status'] = array('eq', $pay_status);
        } elseif ($pay_status == 2) {                      //已付首款
            $map['c.pay_status'] = array('eq', $pay_status);

        }

        //要查询的列表
        $cols = "o.order_id,o.order_no,o.status,o.car_id,o.last_time,o.first_pay_status,o.fail_type,
            c.car_id,c.car_no,c.plate_suffix,c.plate_prefix,c.location_area,c.brand_id,c.series_id,c.model_id,co.seller_name,co.phone,co.sign_reserve_time,
            c.vin,c.car_color,c.accident_level,c.transfer_limit,c.composite_state,c.history_state,c.first_money,c.tail_money,c.car_source,c.pay_status,c.three_in_one,
            co.sign_reserve_province,co.sign_reserve_store,co.sign_service_method,co.sign_date,
            co.sign_reserve_city,co.sign_reserve_area,co.sign_reserve_address,co.deliver_id,o.is_sign_tracing,co.comefrom,co.comefrom_url,
            cd.contact_person,du.uid,
            em.real_name as checker_name,em.mobile as checker_mobile,
            di.issue_id,di.man_id,di.issue_type,
            rc.condition_checker,rc.procedure_checker,rc.next_trace_time,rc.recheck_time,rc.remark as recheck_remark,
            emrc.real_name as condition_checker_name";
        $prefix = C('DB_PREFIX');
        $total = M('order')->alias('o')
            ->join($prefix . "cars as c ON c.car_id=o.car_id")
            ->join('LEFT JOIN ' . $prefix . "car_owner as co ON co.owner_id=c.owner_id")
            ->join('LEFT JOIN ' . $prefix . "dealer_auctioned as re ON re.order_id=o.order_id")
            ->join('LEFT JOIN ' . $prefix . "car_dealer as cd ON cd.dealer_id=re.dealer_id")
            ->join($prefix . "dealer_user as du ON cd.dealer_id=du.dealer_id")
            ->join('LEFT JOIN ' . $prefix . "employee as em ON em.emp_id=co.checker_id")
            ->join('LEFT JOIN ' . $prefix . "dealer_issue as di ON di.order_id=o.order_id")
            ->join('LEFT JOIN ' . $prefix . "recheck as rc ON rc.car_id=c.car_id")
            ->join('LEFT JOIN ' . $prefix . "employee as emrc ON emrc.emp_id=rc.condition_checker")
            ->where($map)->count();

        $list = M('order')->alias('o')->field($cols)
            ->join($prefix . "cars as c ON c.car_id=o.car_id")
            ->join('LEFT JOIN ' . $prefix . "car_owner as co ON co.owner_id=c.owner_id")
            ->join('LEFT JOIN ' . $prefix . "dealer_auctioned as re ON re.order_id=o.order_id")
            ->join('LEFT JOIN ' . $prefix . "car_dealer as cd ON cd.dealer_id=re.dealer_id")
            ->join($prefix . "dealer_user as du ON cd.dealer_id=du.dealer_id")
            ->join('LEFT JOIN ' . $prefix . "dealer_issue as di ON di.order_id=o.order_id")
            ->join('LEFT JOIN ' . $prefix . "employee as em ON em.emp_id=co.checker_id")
            ->join('LEFT JOIN ' . $prefix . "recheck as rc ON rc.car_id=c.car_id")
            ->join('LEFT JOIN ' . $prefix . "employee as emrc ON emrc.emp_id=rc.condition_checker")
            ->where($map)->limit($size)->page($page)->order($order)->select();
//         echo M()->getLastSql();
        if(!empty($list)){
            $dealer = new Dealer();
            $list = $dealer->get_contact_mobile_byAntNest($list);
        }
        $cm = new CarModel();
        $addr = new Address();
        //数据处理
        if (!empty($list)) {
            foreach ($list as $key => $val) {
                $list[$key] = $val;
                if ($list[$key]['is_sign_tracing'] == 0) {
                    $list[$key]['sign_reserve_time'] = transform_date($val['sign_reserve_time'], 1);
                }
                $list[$key]['location_area_name'] = $addr->get_name_by_code($val['location_area']);
                $list[$key]['car_plate_number'] = C('PLATE_PREFIX')[$val['plate_prefix']] . $val['plate_suffix'];
                $brand = $cm->get_model_by_id($val['brand_id'], 'brand');
                $series = $cm->get_model_by_id($val['series_id'], 'series');
                $model = $cm->get_model_by_id($val['model_id']);
                if ($val['sign_service_method'] == 2) {
                    $province = $addr->get_name_by_code($val['sign_reserve_province']);
                    $city = $addr->get_name_by_code($val['sign_reserve_city']);
                    $area = $addr->get_name_by_code($val['sign_reserve_area']);
                    $list[$key]['address'] = $province . " " . $city . " " . $area . " " . $val['sign_reserve_address'];
                } elseif ($val['sign_service_method'] == 3) {
                    $list[$key]['address'] = C('STORE.' . $val['sign_reserve_store']);
                } else {
                    $list[$key]['address'] = "未知";
                }
                $list[$key]['model'] = $brand['name'] . ' ' . $series['name'] . ' ' . $model['name'];
                if (!empty($params['auth'])) {
                    $deliver = Employee::user_info_id($val['deliver_id']);
                    $list[$key]['deliver_name'] = $deliver['real_name'];
                }
                //付款状态
                if ($val['pay_status'] == 2) {
                    if ($val['car_source'] == 1) {                //4s店 100%
                        $pay_status_type = 21;
                    } elseif ($val['car_source'] == 2) {           //个人 50%
                        if ($val['three_in_one'] == 1) {
                            $pay_status_type = 22;
                        } else {                                  //三证不合一 已付首款（0%）
                            $pay_status_type = 23;
                        }
                    }
                }
                $list[$key]['pay_status'] = C("ORDER_PAY_STATUS")[$val['pay_status']];
                $list[$key]['pay_status_code'] = $val['pay_status'];
                $list[$key]['pay_status_type'] = $pay_status_type;
            }
        }
        $result = array(
            'list' => $list,
            'total' => $total
        );
        return $result;
    }

    /**
     * 获取车商争议数据详情
     *
     * 拍单、车源、车主信息、评估师信息、复检信息、验车信息
     *
     * @param int $issueStatus 车商争议数据状态(0:待处理, 1:协商成功 , 2:协商失败)
     *
     * @return fix
     **/
    public function issue_dealer_detail($issue_id)
    {
        $this->checkOrderID();
        //要查询的详情
        $cols = "o.order_id,o.order_no,o.status,o.car_id,o.bid_best_price,o.bidding_best_price,o.bidding_end_time,o.bidding_start_time,o.act_elapsed_time,o.first_pay_status,o.is_consult,o.company_subsidies,
            o.success_price,o.owner_confirm_service_id,o.fail_type,o.is_self_confirm,o.last_time,o.transfer_type,
            c.car_no,c.plate_suffix,c.plate_prefix,c.location_area,c.brand_id,c.series_id,c.model_id,co.seller_name,co.phone,co.sign_reserve_time,c.emission,c.first_reg_date,c.pointer_mileage,c.reg_city,
            c.vin,c.car_color,c.accident_level,c.transfer_limit,c.composite_state,c.history_state,c.first_money,c.tail_money,c.car_source,c.three_in_one,
            co.sign_reserve_province,co.sign_reserve_store,co.sign_service_method,co.sign_date,co.check_date,co.owner_id,co.owner_type,co.contact_person as owner_contact_person,
            co.sign_reserve_city,co.sign_reserve_area,co.sign_reserve_address,co.deliver_id,o.is_sign_tracing,co.comefrom,co.comefrom_url,
            cd.dealer_id,cd.contact_person,du.uid,cd.level,cd.bail_amount,
            em.real_name as checker_name,em.mobile as checker_mobile,
            dc.check_id,dc.man_id,dc.status as check_status,dc.check_time as check_done_time,dc.updatetime as check_update_time,dc.emp_id as check_done_empid,
            dc.remark as dealer_check_remark,dc.updatetime,
            di.issue_id,di.man_id,di.issue_type,di.status as issue_status,di.updatetime as issue_done_time,di.emp_id as issue_done_empid,di.cut_down_price,di.remark,di.updatetime,
            emdi.real_name as issue_done_emp,
            crl.driver_name,crl.driver_company,crl.driver_phone,crl.depart_time,
            rc.condition_checker,rc.procedure_checker,rc.next_trace_time,rc.recheck_time,rc.remark as recheck_remark,
            emrc.real_name as condition_checker_name,pl.emp_id,pl.pay_type,pl.status as pay_status,pl.last_update as pay_time,c.pay_status as car_pay_status";
        $prefix = C('DB_PREFIX');
        $map = array();
        $map['o.order_id'] = array('eq', $this->order_id);
        $map['re.status'] = array('eq', 0);
        $map['di.issue_id'] = array('eq', $issue_id);
        // $cond = "o.order_id='" . $this->order_id . "' and re.status=0";
        $res = M('order')->alias('o')->field($cols)
            ->join($prefix . "cars as c ON c.car_id=o.car_id")
            ->join($prefix . "car_owner as co ON co.owner_id=c.owner_id")
            ->join($prefix . "dealer_auctioned as re ON re.order_id=o.order_id")
            ->join('LEFT JOIN ' . $prefix . "car_dealer as cd ON cd.dealer_id=re.dealer_id")
            ->join('LEFT JOIN ' . $prefix . "dealer_user as du ON cd.dealer_id=du.dealer_id")
            ->join('LEFT JOIN ' . $prefix . "employee as em ON em.emp_id=co.checker_id")
            ->join('LEFT JOIN ' . $prefix . "car_dealer_check as dc ON dc.order_id=o.order_id")
            ->join('LEFT JOIN ' . $prefix . "dealer_issue as di ON di.order_id=o.order_id")
            ->join('LEFT JOIN ' . $prefix . "employee as emdi ON emdi.emp_id=di.emp_id")
            ->join('LEFT JOIN ' . $prefix . "car_return_log as crl ON crl.car_id=o.car_id")
            ->join('LEFT JOIN ' . $prefix . "recheck as rc ON rc.car_id=c.car_id")
            ->join('LEFT JOIN ' . $prefix . "employee as emrc ON emrc.emp_id=rc.condition_checker")
            ->join('LEFT JOIN ' . $prefix . "pay_log as pl ON o.car_id = pl.car_id")
            ->where($map)->find();
        if(!empty($res)){
            $d = new Dealer();
            $res = $d->get_contact_mobile_byAntNestfind($res);
        }
// return M('order')->getLastSql();
// echo M()->getlastsql();
        $cm = new CarModel();
        $brand = $cm->get_model_by_id($res['brand_id'], 'brand');
        $series = $cm->get_model_by_id($res['series_id'], 'series');
        $model = $cm->get_model_by_id($res['model_id']);
        $res['model'] = $brand['name'] . ' ' . $series['name'] . ' ' . $model['name'];
        $res['format_reserve_price'] = format_money($res['reserve_price']);
        $res['format_best_price'] = format_money($res['bidding_best_price'] > $res['bid_best_price'] ? $res['bidding_best_price'] : $res['bid_best_price']);
        $res['best_price'] = $res['bidding_best_price'] > $res['bid_best_price'] ? $res['bidding_best_price'] : $res['bid_best_price'];
        $res['car_color'] = C('CAR_COLOR.' . $res['car_color']);
        $res['emission'] = C('INT_EMISSION_STD.' . $res['emission']);
        $res['plate_prefix'] = C('PLATE_PREFIX.' . $res['plate_prefix']);
        $res['pointer_mileage'] = round($res['pointer_mileage'] / 10000, 2);
        $addr = new Address();
        $res['location_area_name'] = $addr->get_name_by_code($res['location_area']);
        $res['reg_city'] = $addr->get_name_by_code($res['reg_city']);
        $res['car_plate_number'] = C('PLATE_PREFIX')[$res['plate_prefix']] . $res['plate_suffix'];
        //付款状态
        if ($res['car_pay_status'] == 2) {
            if ($res['car_source'] == 1) {                //4s店 100%
                $pay_status_type = 21;
            } elseif ($res['car_source'] == 2) {           //个人 50%
                if ($res['three_in_one'] == 1) {
                    $pay_status_type = 22;
                } else {                                  //三证不合一 已付首款（0%）
                    $pay_status_type = 23;
                }
            }
        }
        $res['pay_status_name'] = C("ORDER_PAY_STATUS")[$res['car_pay_status']];
        $res['pay_status_code'] = $pay_status_type;
        // $res['pay_status_type'] = $pay_status_type;

        if ($res['emp_id'] > 0) {
            $employee = \AuctionCore\Account\Back\Employee::user_info_id($res['emp_id']);
            $res['pay_man'] = $employee['real_name'];
        }
        $res['owner_type_name'] = C('OWNER_TYPE_NAME')[$res['owner_type']];
        return $res;
    }

    /**
     * 获取车辆所有拍单中最近一次违约仲裁人信息
     *
     * @param int $order_id_arr
     *
     * @return array
     */
    public static function get_near_arbitrator($order_id_arr = [])
    {
        if (empty($order_id_arr)) {
            return false;
        }
        $prefix = C('DB_PREFIX');
        $cols = 'emdi.mobile as issue_done_phone,emdi.real_name as issue_done_emp';
        $map['di.order_id'] = ['in', $order_id_arr];
        return M('dealer_issue')->alias('di')->field($cols)
            ->join('LEFT JOIN ' . $prefix . "employee as emdi ON emdi.emp_id=di.emp_id")
            ->where($map)
            ->order('issue_id DESC')
            ->find();
    }

    /**
     * 添加车商争议记录
     *
     * 更改争议处理状态，"协商补偿"=>"协商成功", "车商违约"=>"协商失败"
     * 协商补偿：如果是金牌车商，可以选择过户类型；当选择车商自过类型时需要记录提车人
     * 车商违约：违约扣款金额上限不得超过2000元
     * 记录备注信息
     *
     * @param  array $data 需更新数据
     *
     * @return   boolean
     */
    public static function add_dealer_issue($data = array())
    {
        //事务开始
        M()->startTrans();
        // 记录车商争议处理结果
        $params = array(
            'order_id' => $data['order_id'],
            'dealer_id' => $data['dealer_id'],
            'issue_type' => $data['issue_type'],
            'deduct_type' => $data['deduct_type'],
            'createtime' => date('Y-m-d H:i:s')
        );
        $dealer_issue = M('dealer_issue');
        $res_dealer_issue = $dealer_issue->add($params);
        $res_order = M('order')->where(['order_id' => $data['order_id']])->setField('dealer_issue_status', 1);
        if ($res_dealer_issue && $res_order !== false) {
            //事务提交
            M()->commit();
            //记录操作日志
            $log = array('order_id' => $data['order_id'], 'dealer_id' => $data['dealer_id'], 'action' => '产生车商争议');
            \AuctionCore\System\SystemLog::add($log);
            return true;
        } else {
            M()->rollback();
            \Think\Log::record('添加车商争议时发生回滚事件！order_id:' . $data['order_id'] . ',dealer_id:' . $data['dealer_id']);
            return false;
        }
    }


    /**
     * 验证参数
     *
     * @param $data
     *
     * @return array $issue_info
     * @throws AuctionException
     */
    private function checkParams($data)
    {
        //验证争议编号
        if (!isset($data['issue_id']) || !is_numeric($data['issue_id'])) {
            AuctionException::make_throw('1700001');
        }
        if (!isset($data['status']) || !is_numeric($data['status'])) {
            AuctionException::make_throw('1700002');
        }

        $issueInfo = self::detail_by_issue_id($data['issue_id']);
        if (empty($issueInfo)) {
            AuctionException::make_throw('1700007');
        }
        if ($issueInfo['status'] != self::$dataStatus['pending']) {
            AuctionException::make_throw('1700004');
        }
        return $issueInfo;
    }

    /**
     * 保存车商争议处理结果
     *
     * 更改争议处理状态，"协商补偿"=>"协商成功", "车商违约"=>"协商失败"
     * 协商补偿：如果是金牌车商，可以选择过户类型；当选择车商自过类型时需要记录提车人
     * 车商违约：违约扣款金额上限不得超过2000元
     * 记录备注信息
     * 争议类型: 1.车况不符;2.超时验车;3.待过户争议;4.结算争议;5.过户中争议;6.待收款争议;7.核实收款争议
     *
     * @param  array $data 需更新数据
     *
     * @return  boolean
     */
    public function save_dealer_issue($data)
    {
        $issueInfo = $this->checkParams($data);
        //事务开始
        M()->startTrans();
        if ($data['status'] == 1) {
            $ret = $this->consultSuccess($issueInfo, $data);
        } else {
            $ret = $this->consultFailed($issueInfo, $data);
        }
        return $ret;
    }

    /**
     * @param $issueInfo
     * @param $data
     *
     * @return bool
     */
    private function consultSuccess($issueInfo, $data)
    {
        $params = array(
            'emp_id' => $data['emp_id'],
            'status' => $data['status'],
            'cut_down_price' => $data['cut_down_price'],
            'remark' => $data['remark'],
            'updatetime' => date('Y-m-d H:i:s')
        );

        //金牌商户可更改过户方式
        if (isset($data['transfer_type']) && $data['transfer_type'] == 1) {
            $params['transfer_type'] = $data['transfer_type'];
            $params['man_id'] = $data['man_id'];

            $dealerInfo = Dealer::get_dealer_by_order_id($data['order_id']);
            $dealer_id = !empty($dealerInfo['dealer_id']) ? $dealerInfo['dealer_id'] : 0;
            $auctionObj = new MyAuctioned($dealer_id);
            $auctionObj->up_by_order_id($data['order_id'], array('man_id' => $data['man_id']));
        }
        //拍单改为协商成功
        $o = new AuOrder($data['order_id']);
        $orderInfo = $o->detail();
        $paramsOrder = array(
            'transfer_type' => $data['transfer_type'],
            'dealer_issue_status' => 2,
        );
        $c = new Car($data['car_id']);
        $carInfo = $c->detail();
        //关闭补偿
        $resDealerCompensate = DealerCompensate::closeCompensate($data['order_id']);
        if ($resDealerCompensate === false) {
            M()->rollback();
            Log::record('车商争议处理,关闭补偿发生回滚事件！issue_id:' . $data['issue_id'] . ',emp_id:' . $data['emp_id']);
            return false;
        }
        //添加新补偿
        $dealer_compensate = array(
            'order_id' => $data['order_id'],
            'dealer_id' => $data['dealer_id'],
            'car_id' => $data['car_id'],
            'compensate_amount' => $data['cut_down_price'],
            'issue_id' => $data['issue_id']
        );
        $DealerCompensate = new DealerCompensate();
        $resDealerCompensate = $DealerCompensate->add_dealer_compensate($dealer_compensate);
        if (!$resDealerCompensate) {
            M()->rollback();
            \Think\Log::record('车商争议,添加补偿记录失败,回滚！issue_id:' . $issueInfo['issue_id'] . ',emp_id:' . $data['emp_id']);
            return false;
        }

        //1:车况不符, 2:超时验车,3:待过户争议,4:结算争议,5:过户中争议,6:待收款争议,7:核实收款争议
        if ($issueInfo['issue_type'] == 1) {
            $paramsOrder['check_car_status'] = 3;
            if ($carInfo['delivery_mode'] == 1) { //先付款后验车
                //直接流转到过户
                if ($carInfo['pay_status'] == 2) { // 已付首款
                    $paramsOrder['status'] = 9;
                    //发送消息
                    $uid = $o->get_uid_by_order();
                    $car_name = $c->get_car_name();
                    $content = "【 " . $car_name . " 】拍单编号：" . $orderInfo['order_no'] . "，付款成功。交付顾问正在过户中，敬请关注。";
                    Inbox::sendMessage($uid, '车辆待过户', $content);
                }
            } else { //先验车后付款
                //写结算记录
                $paramsProceed = array(
                    'order_id' => $data['order_id'],
                );
                $resProceed = \AuctionCore\Finance\Collection::add($paramsProceed);
                if ($resProceed === false) {
                    M()->rollback();
                    \Think\Log::record('车商争议成功,添加付款记录发生回滚事件！issue_id:' . $issueInfo['issue_id'] . ',emp_id:' . $data['emp_id']);
                    return false;
                }
            }
        } elseif ($issueInfo['issue_type'] == 2) {
            //车商验车由关闭改为待验车,跟踪日志
            $paramsDealerCheckCar = ['status' => 1];
            $paramsOrder['check_car_status'] = 2;
            $resDealerCheckCar = M("car_dealer_check")->where(['order_id' => $data['order_id']])->save($paramsDealerCheckCar);
            if ($resDealerCheckCar === false) {
                M()->rollback();
                \Think\Log::record('车商争议,修改车商验车记录失败,回滚！issue_id:' . $issueInfo['issue_id'] . ',emp_id:' . $data['emp_id']);
                return false;
            }
        } elseif ($issueInfo['issue_type'] == 3 || $issueInfo['issue_type'] == 5) {
            //继续过户,过户跟踪日志
            $paramsTransfer = [];
            if ($issueInfo['issue_type'] == 3) {
                $paramsTransfer['result'] = 0;
            } elseif ($issueInfo['issue_type'] == 5) {
                $paramsTransfer['result'] = 1;
            }

            $resTransfer = M('transfer_log')->where(['order_id' => $data['order_id'], 'result' => 3])->save($paramsTransfer);
            if ($resTransfer === false) {
                M()->rollback();
                \Think\Log::record('车商争议,修改过户记录失败,回滚！issue_id:' . $issueInfo['issue_id'] . ',emp_id:' . $data['emp_id']);
                return false;
            }
        } elseif ($issueInfo['issue_type'] == 4 || $issueInfo['issue_type'] == 6 || $issueInfo['issue_type'] == 7) {
            //继续收款
            if ($issueInfo['issue_type'] == 4) {
                $paramsOrder['dealer_pay_status'] = 0;
            } elseif ($issueInfo['issue_type'] == 6) {
                $paramsOrder['dealer_pay_status'] = 1;
            } elseif ($issueInfo['issue_type'] == 7) {
                $paramsOrder['dealer_pay_status'] = 2;
            }
        }
        $resOrder = $o->update($paramsOrder);
        if ($resOrder === false) {
            M()->rollback();
            \Think\Log::record('车商争议处理,更新拍单记录失败,回滚！issue_id:' . $issueInfo['issue_id'] . ',emp_id:' . $data['emp_id']);
            return false;
        }
        $res_dealer_issue = M('dealer_issue')->where(array('issue_id' => $data['issue_id']))->save($params);
        if ($res_dealer_issue === false) {
            M()->rollback();
            \Think\Log::record('车商争议处理,更新拍单记录失败,回滚！issue_id:' . $issueInfo['issue_id'] . ',emp_id:' . $data['emp_id']);
            return false;
        }
        M()->commit();
        Car::add_car_trace_log($data['car_id'], ['action_name' => '车商争议，协商成功', 'emp_id' => $data['emp_id']]);
        AuOrder::add_order_trace_log($data['order_id'], ['action_name' => '车商争议，协商成功', 'emp_id' => $data['emp_id']]);
        return true;
    }

    private function consultFailed($issueInfo, $data)
    {
        $o = new AuOrder($data['order_id']);
        $order_info = $o->detail();
        $params = array(
            'emp_id' => $data['emp_id'],
            'status' => $data['status'],
            'cut_down_price' => $data['cut_down_price'],
            'remark' => $data['remark'],
            'updatetime' => date('Y-m-d H:i:s')
        );
        if (!is_numeric($params['cut_down_price']) || $params['cut_down_price'] > 2000) {
            M()->rollback();
            AuctionException::make_throw('1700003');
        }
        $res_dealer_issue = M('dealer_issue')->where(array('issue_id' => $data['issue_id']))->save($params);
        if ($res_dealer_issue === false) {
            M()->rollback();
            \Think\Log::record('车商争议处理,更新争议录失败,回滚！issue_id:' . $issueInfo['issue_id'] . ',emp_id:' . $data['emp_id']);
            return false;
        }
        //失败类型(1,车主要求重拍 2,车主不卖了(确) 3,签约失败 4,车商违约 5,过户失败 6,车主不卖了(流) 7,我方违约 8,收款失败
        $paramsOrder = array();
        $paramsOrder['status'] = 12;
        $paramsOrder['dealer_issue_status'] = $data['status'] == 2 ? 3 : 4;  //争议处理结果 3 协商失败4我方违约
        if ($issueInfo['issue_type'] == 1 || $issueInfo['issue_type'] == 2) {
            $paramsOrder['check_car_status'] = 5;
            $paramsOrder['fail_type'] = 4;
        } elseif ($issueInfo['issue_type'] == 3 || $issueInfo['issue_type'] == 5) {
            $paramsOrder['fail_type'] = 5;
        } elseif ($issueInfo['issue_type'] == 4 || $issueInfo['issue_type'] == 6 || $issueInfo['issue_type'] == 7) {
            $paramsOrder['fail_type'] = 8;
            $paramsOrder['dealer_pay_status'] = 5;
        }

        //自收车辆
//        $dealer = new \AuctionCore\CarDealer\Dealer($order_info['success_dealer_id']);
//        $dealer_info = $dealer->get_dealer_info_by_dealer_id($order_info['success_dealer_id']);
        $car = new Car($data['car_id']);
        $car_detail = $car->detail();
        if ($car_detail['is_self_receive'] == 1) {
            //更新车辆信息
            $c = new Car($order_info['car_id']);
            $car_data = [
                'is_self_receive' => 1,
                'self_receive_dealer_id' => $order_info['success_dealer_id']
            ];
            $car_ret = $c->update($car_data);
            if ($car_ret === false) {
                M()->rollback();
                $this->helpJsonResult(500, "操作失败");
            }
            //添加自收车辆记录
            $self_receive_car_info = [
                'car_id' => $data['car_id'],
                'order_id' => $data['order_id'],
                'compensate_type' => ($data['status'] == 2) ? 2 : 1,
                'issue_id' => $issueInfo['issue_id'],
                'self_type' => 3
            ];
            $self_receive_car = new \AuctionCore\CarResource\SelfReceiveCar();
            $self_receive_car_ret = $self_receive_car->add_self_receive_car($self_receive_car_info);
            if (!$self_receive_car_ret) {
                M()->rollback();
                AuctionException::make_throw('1800002'); //添加违约自收处理记录失败
            }
        } else {
            //添加违约车辆记录
            $breach_car_info = array(
                'car_id' => $data['car_id'],
                'issue_id' => $data['issue_id']
            );
            //退车类型（1、我方违约 - 赔偿 2、车商违约 - 扣除）
            $breach_car_info['compensate_type'] = ($data['status'] == 2) ? 2 : 1;
            $resCar = BreachCar::create($breach_car_info);
            if ($resCar < 1) {
                M()->rollback();
                AuctionException::make_throw('1800001'); //添加违约处理记录失败
            }
        }

        $resOrder = $o->update($paramsOrder);
        if ($resOrder === false) {
            M()->rollback();
            \Think\Log::record('车商争议处理,更新拍单时发生回滚事件！issue_id:' . $data['issue_id'] . ',emp_id:' . $data['emp_id']);
            return false;
        }


        //关闭车商补偿
        $resDealerCompensate = DealerCompensate::closeCompensate($data['order_id']);
        if ($resDealerCompensate === false) {
            M()->rollback();
            Log::record('车商争议处理,关闭补偿发生回滚事件！issue_id:' . $data['issue_id'] . ',emp_id:' . $data['emp_id']);
            return false;
        }

        //贷款的取消贷款
        if ($order_info['dealer_pay_mode'] == 2) {
            $cancel_res = $this->cancel_loan($data['order_id']);
            if ($cancel_res == false) {
                M()->rollback();
                Log::record('车商争议处理,取消贷款发生回滚事件！issue_id:' . $data['issue_id'] . ',emp_id:' . $data['emp_id']);
                return false;
            }
        }
        if ($data['status'] == 2) { //车商违约 扣款
            $ret = $this->dealerDefault($data, $order_info);
        } else { //我方违约 补偿
            $ret = $this->ourDefault($data, $order_info);
        }
        return $ret;
    }

    /**
     * @param $data
     * @param $orderInfo
     *
     * @return bool
     */
    private function dealerDefault($data, $orderInfo)
    {
        if ($orderInfo['dealer_pay_status'] == 3 && $orderInfo['dealer_pay_mode'] == 1) {
            //已收车款-扣除金额后的金额 退到退车商款表中
            $refundRes = $this->addDealerRefund($data, 2);
            if ($refundRes == false) return false;
        } else {
            //扣保证金
            $assertCenter = new AssetCenter($data['dealer_id']);
            $assertParams = array(
                'order_id' => $data['order_id'],
                'dealer_id' => $data['dealer_id'],
                'order_no' => $orderInfo['order_no'],
                'occur_money' => $data['cut_down_price'], // 发生金额
                'use_detail' => $data['remark'], // 应用明细
            );
            try {
                $resViolateBail = $assertCenter->occurViolate($assertParams);
            } catch (AuctionException $ex) {
                M()->rollback();
                AuctionException::make_throw($ex->getCode()); //获取车商异常
            }

            if ($resViolateBail === false) {
                M()->rollback();
                \Think\Log::record('处理车商争议时发生回滚事件！issue_id:' . $data['issue_id'] . ',emp_id:' . $data['emp_id']);
                return false;
            }

            if ($orderInfo['dealer_pay_mode'] == 2) { // 贷款退首付款
                $l = new Loan();
                $loan_log = $l->get_loan_detail($orderInfo['order_id']);
                if ($loan_log['first_pay_money'] > 0) {
                    $refundRes = $this->addDealerRefund($data, 2);
                    if ($refundRes === false) return false;
                }
            }
        }

        M()->commit();
        Car::add_car_trace_log($data['car_id'], ['action_name' => '车商争议，违约扣款', 'emp_id' => $data['emp_id']]);
        AuOrder::add_order_trace_log($data['order_id'], ['action_name' => '车商争议，违约扣款', 'emp_id' => $data['emp_id']]);
        return true;
    }

    /**
     * @param $data
     * @param $orderInfo
     *
     * @return bool
     */
    private function ourDefault($data, $orderInfo)
    {
        $is_free = false; //是否需要解冻保证金
        if ($orderInfo['dealer_pay_status'] == 3 && $orderInfo['dealer_pay_mode'] == 1) {
            //车商补偿 + 车款
            $refundRes = $this->addDealerRefund($data, 1);
            if ($refundRes == false) return false;
        } else {
            //贷款的退首付款
            if ($orderInfo['dealer_pay_mode'] == 2) {
                $l = new Loan();
                $loan_log = $l->get_loan_detail($orderInfo['order_id']);
                if ($loan_log['first_pay_money'] > 0) {
                    $refundRes = $this->addDealerRefund($data, 1);
                    if ($refundRes == false) return false;
                } else {
                    $dc_res = $this->addDealerCompensate($data);
                    if ($dc_res === false) return false;
                }
            } else {
                // 添加补偿
                $dc_res = $this->addDealerCompensate($data);
                if ($dc_res === false) return false;
            }
            $is_free = true;
        }
        M()->commit();
        if ($is_free == true) {
            //解冻保证金
            try {
                AssetCenter::free_all($data['order_id']);
            } catch (AuctionException $ex) {
                M()->rollback();
                AuctionException::make_throw($ex->getCode()); //获取车商异常
            }
        }
        Car::add_car_trace_log($data['car_id'], ['action_name' => '我方违约，违约补偿', 'emp_id' => $data['emp_id']]);
        AuOrder::add_order_trace_log($data['order_id'], ['action_name' => '我方违约，违约补偿', 'emp_id' => $data['emp_id']]);
        return true;
    }


    /**
     * @param $params
     *
     * @return bool|mixed
     */
    public function getDealerIssueByParams($params)
    {
        if (empty($params)) return false;
        return M("dealer_issue")->where($params)->find();
    }

    /**
     * 贷款取消 16-08-18
     */
    public function cancel_loan($order_id)
    {
        $o = new AuOrder($order_id);
        $loan_log = $o->get_loan_log();
        //贷款前置状态判断
        $data = array();
        $data['xm_list_code'] = (string)$loan_log['xm_list_code'];
        $data['product_id'] = C('PROD_CAR_OLD_CLCW.0');
        $ximu = new XimuApi();
        $res = $ximu->_get("ORDER", "cancellist", $data);
        if ($res['code'] == 200) {
            $res1 = $o->cancel_loan();
        }
        return $res1;
    }

    /**
     * 添加车商退款
     *
     * @param $data
     * @param $refund_type
     *
     * @return bool|mixed
     */
    private function addDealerRefund($data, $refund_type)
    {
        $dealer_refund = array(
            'order_id' => $data['order_id'],
            'dealer_id' => $data['dealer_id'],
            'car_id' => $data['car_id'],
            'refund_type' => $refund_type,
            'issue_id' => $data['issue_id'],
            'consult_amount' => $data['cut_down_price']
        );
        $DealerRefund = new DealerRefund();
        $refundRes = $DealerRefund->add_dealer_refund($dealer_refund);
        if ($refundRes == false) {
            M()->rollback();
            Log::record('车商争议,车商退款时发生回滚事件！issue_id:' . $data['issue_id'] . ',emp_id:' . $data['emp_id']);
        }
        return $refundRes;
    }

    /**
     * 添加车商补偿
     *
     * @param $data
     *
     * @return bool|mixed
     */
    private function addDealerCompensate($data)
    {
        $dealerCompensateData = array(
            'order_id' => $data['order_id'],
            'dealer_id' => $data['dealer_id'],
            'car_id' => $data['car_id'],
            'compensate_amount' => $data['cut_down_price'],
            'issue_id' => $data['issue_id']
        );
        $DealerCompensate = new DealerCompensate();
        $dcRes = $DealerCompensate->add_dealer_compensate($dealerCompensateData);
        if ($dcRes === false) {
            M()->rollback();
            Log::record('车商争议,我方违约时发生回滚事件！issue_id:' . $data['issue_id'] . ',emp_id:' . $data['emp_id']);
        }
        return $dcRes;
    }

}
